<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSwitch,
  ElTable,
  ElTableColumn,
} from 'element-plus';

// 导入API
import {
  createSubsidyConfig,
  getSubsidyConfigList,
  toggleSubsidyConfigStatus,
  updateSubsidyConfig,
} from '#/api/subsidyConfig';

// 页面常量定义
const TEXT = {
  title: '补贴配置管理',
  add: '新增补贴配置',
  edit: '编辑补贴配置',
  delete: '删除补贴配置',
  areaType: '区域类型',
  amount: '每公里补贴金额',
  effectiveDate: '生效时间',
  status: '状态',
  confirm: '确认',
  cancel: '取消',
  deleteConfirm: '确定要删除 {0} 补贴配置吗？',
  deleteSuccess: '删除成功',
  operationSuccess: '操作成功',
} as const;

// 表单数据
const formData = ref({
  areaType: 'in' as 'in' | 'out',
  amount: '',
  effectiveDate: '',
});

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

// 每页条数选项
const pageSizeOptions = [10, 20, 30, 50];

// 是否显示新增/编辑弹窗
const dialogVisible = ref(false);
const dialogTitle = ref('新增补贴配置');
const isEditing = ref(false);
const currentEditId = ref<null | number>(null);

// 区域类型选项
const areaTypeOptions = [
  { label: '省内', value: 'in' },
  { label: '省外', value: 'out' },
];

// 是否有数据
const hasData = computed(() => tableData.value.length > 0);

// 监听分页变化
watch(
  () => [pagination.value.currentPage, pagination.value.pageSize],
  () => {
    fetchSubsidyConfigData();
  },
  { deep: true },
);

// 获取补贴配置列表
const fetchSubsidyConfigData = async () => {
  loading.value = true;

  try {
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
    };

    const response = await getSubsidyConfigList(params);

    tableData.value = response.list || [];
    pagination.value.total = response.total || 0;

    // 如果没有数据，显示提示信息
    if (!hasData.value) {
      ElMessage.info('暂无补贴配置数据');
    }
  } catch (error) {
    console.error('获取补贴配置列表失败:', error);
    ElMessage.error('获取数据失败，请重试');
    tableData.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = TEXT.add;
  isEditing.value = false;
  currentEditId.value = null;
  formData.value = {
    areaType: 'in',
    amount: '',
    effectiveDate: '',
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  dialogTitle.value = TEXT.edit;
  isEditing.value = true;
  currentEditId.value = row.id;
  formData.value = {
    areaType: row.areaType as 'in' | 'out',
    amount: String(row.amount),
    effectiveDate: row.effectiveDate,
  };
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    TEXT.deleteConfirm.replace('{0}', row.areaTypeText),
    TEXT.confirm,
    {
      confirmButtonText: TEXT.confirm,
      cancelButtonText: TEXT.cancel,
      type: 'warning',
    },
  )
    .then(() => {
      // TODO: 实现删除功能
      ElMessage.success(TEXT.deleteSuccess);
      fetchSubsidyConfigData();
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 处理状态切换
const handleStatusChange = async (row: any) => {
  const newStatus = row.status === 'enable' ? 'disable' : 'enable';
  const newStatusText = row.status === 'enable' ? '停用' : '启用';

  try {
    await toggleSubsidyConfigStatus(row.id, { status: newStatus });
    row.status = newStatus;
    row.statusText = newStatusText;
    ElMessage.success(`${newStatusText}成功`);
  } catch (error) {
    console.error('切换状态失败:', error);
    ElMessage.error('操作失败，请重试');
    // 恢复原状态
    row.status = row.status === 'enable' ? 'disable' : 'enable';
    row.statusText = row.status === 'enable' ? '启用' : '停用';
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page;
};

// 处理每页条数变化
const handlePageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1; // 切换条数时重置到第一页
};

// 处理表单提交
const handleSubmit = async () => {
  try {
    // 验证表单
    if (!formData.value.amount || !formData.value.effectiveDate) {
      ElMessage.warning('请填写完整信息');
      return;
    }

    if (isEditing.value && currentEditId.value) {
      // 编辑
      await updateSubsidyConfig(currentEditId.value, {
        amount: Number.parseFloat(formData.value.amount),
        effectiveDate: formData.value.effectiveDate,
      });
      ElMessage.success('编辑成功');
    } else {
      // 新增
      await createSubsidyConfig({
        areaType: formData.value.areaType,
        amount: Number.parseFloat(formData.value.amount),
        effectiveDate: formData.value.effectiveDate,
      });
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    fetchSubsidyConfigData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
};

// 页面初始化
onMounted(() => {
  fetchSubsidyConfigData();
});
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-5">
    <!-- 筛选区域 -->
    <ElCard class="mb-5 rounded-xl border-0 shadow-lg">
      <div class="flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-800">
          {{ TEXT.title }}
        </h3>
        <ElButton type="primary" @click="handleAdd" class="px-4">
          {{ TEXT.add }}
        </ElButton>
      </div>
    </ElCard>

    <!-- 数据展示区 -->
    <ElCard class="rounded-xl border-0 shadow-lg">
      <div class="p-4">
        <!-- 数据表格 -->
        <ElTable
          v-loading="loading"
          :data="tableData"
          class="subsidy-config-table overflow-hidden rounded-lg"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#374151',
            fontWeight: '600',
            borderBottom: '2px solid #e5e7eb',
          }"
          :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
          empty-text="暂无补贴配置数据"
        >
          <ElTableColumn prop="id" label="配置ID" width="80" align="center" />
          <ElTableColumn
            prop="areaTypeText"
            :label="TEXT.areaType"
            width="100"
            align="center"
          />
          <ElTableColumn
            prop="amount"
            :label="TEXT.amount"
            width="150"
            align="center"
          >
            <template #default="{ row }"> {{ row.amount }} 元/公里 </template>
          </ElTableColumn>
          <ElTableColumn
            prop="effectiveDate"
            :label="TEXT.effectiveDate"
            width="120"
            align="center"
          />
          <ElTableColumn
            prop="statusText"
            :label="TEXT.status"
            width="100"
            align="center"
          >
            <template #default="{ row }">
              <ElSwitch
                v-model="row.status"
                active-value="enable"
                inactive-value="disable"
                @change="handleStatusChange(row)"
                active-text="启用"
                inactive-text="停用"
              />
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="updateTime"
            label="操作"
            width="200"
            align="center"
            fixed="right"
          >
            <template #default="{ row }">
              <div class="flex justify-center gap-2">
                <ElButton
                  size="small"
                  type="primary"
                  text
                  @click="handleEdit(row)"
                >
                  编辑
                </ElButton>
                <ElButton
                  size="small"
                  type="danger"
                  text
                  @click="handleDelete(row)"
                >
                  删除
                </ElButton>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>

        <!-- 分页 -->
        <div v-if="hasData" class="mt-4 flex items-center justify-between">
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-600">
              显示
              {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到
              {{
                Math.min(
                  pagination.currentPage * pagination.pageSize,
                  pagination.total,
                )
              }}
              条，共 {{ pagination.total }} 条
            </span>
            <ElSelect
              v-model="pagination.pageSize"
              @change="handlePageSizeChange"
              class="w-20"
              size="small"
            >
              <ElOption
                v-for="size in pageSizeOptions"
                :key="size"
                :label="`${size} 条/页`"
                :value="size"
              />
            </ElSelect>
          </div>
          <ElPagination
            v-model:current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            layout="prev, pager, next, jumper"
            background
          />
        </div>
      </div>
    </ElCard>

    <!-- 新增/编辑弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm
        :model="formData"
        label-width="120px"
        label-position="left"
        class="subsidy-form"
      >
        <ElFormItem :label="TEXT.areaType" required>
          <ElSelect
            v-model="formData.areaType"
            :placeholder="TEXT.areaType"
            :disabled="isEditing"
          >
            <ElOption
              v-for="option in areaTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="TEXT.amount" required>
          <ElInput
            v-model="formData.amount"
            type="number"
            :placeholder="TEXT.amount"
            :min="0"
            :step="0.1"
          >
            <template #suffix>元/公里</template>
          </ElInput>
        </ElFormItem>
        <ElFormItem :label="TEXT.effectiveDate" required>
          <ElDatePicker
            v-model="formData.effectiveDate"
            type="date"
            :placeholder="TEXT.effectiveDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="handleCancel">取消</ElButton>
          <ElButton type="primary" @click="handleSubmit">确定</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 响应式优化 */
@media (max-width: 768px) {
  .flex-wrap {
    flex-direction: column;
    align-items: stretch;
  }

  .grid-cols-3 {
    grid-template-columns: repeat(1, 1fr);
  }

  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}

/* 自定义样式 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.subsidy-config-table .el-table__row:nth-child(even)) {
  background-color: #f9fafb;
}

:deep(.el-loading-mask) {
  background-color: rgb(255 255 255 / 80%);
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #10b981;
  border-color: #10b981;
}

:deep(.el-switch .el-switch__core) {
  background-color: #d1d5db;
  border-color: #d1d5db;
}

:deep(.el-switch.is-checked .el-switch__action) {
  transform: translateX(20px);
}

/* 禁用删除按钮样式 */
:deep(.el-button:disabled) {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}
</style>
